import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";

import download from "@/utils/download";
import { connect } from "dva";
import { exportQAHistories } from "@/services/download";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Card, Row, Col, Form, Input, Button, message, Icon, Checkbox, Table, Tag, Select, Modal, Radio, Spin, Upload, Tooltip, Tabs, } from "antd";
import styles from "./index.less";
import x from "@/assets/medicalKnowledge/ABC.png";
import axios from "axios";
import emptys from "@/assets/icons/emptys.png";
import importIcon from "@/assets/importIcon.png";
import exportIcon from "@/assets/exportIcon.png";
import UserSession from "@/UserSession";

const Search = Input.Search;
const { TabPane } = Tabs;
const FormItem = Form.Item;
class BusinessDictionary extends Component {
	constructor(props) {
		super(props);
		this.state = {
			login: false,
			thesaurusList: [],
			pageSize: 9999999,
			page: 1,
			showModel: false,
			showModelA: false,
			searchValue: null,
			total: 0,
			fileList: [],
			pdx: null,
			uploading: false,
		};
		this.columns = [
			{
				title: "",
				width: "calc(10vw)",
				dataIndex: "",
			},
			{
				title: "业务词",
				width: "calc(70vw)",
				dataIndex: "name",
			},
			{
				title: "操作",
				width: "calc(20vw)",
				render: (text, item) => (
					<div className={styles.buttongl} onClick={text => this.handleDeletes(item)}>
						<span>
							<Icon size='small' type='delete' style={{ marginRight: 5 }} />
						</span>
						<span>
							<FormattedMessage id='app.wordTroughManage.delete' />
						</span>
					</div>
				),
			},
		];
	}

	// eslint-disable-next-line react/sort-comp
	fetch = (search = "", page = 1, limit = 99999999) => {
		this.setState({ login: true });
		const { dispatch, currentUser } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "businessDictionary/fetch",
				payload: { current: page, size: limit },
				callback: (res) => {
					this.setState({ thesaurusList: res.records ? res.records : [], total: res.total, pdx: null, login: false, });
				},
			});
		});
	};

	componentDidMount(val) {
		this.fetch(val);
	}

	answerDetail = () => {
		if (this.state.total === 0) {
			message.error("空列表无法导出！");
		} else {
			const { dispatch, currentUser } = this.props;
			const { searchValue } = this.state;
			const data = { search: searchValue };
			dispatch({
				type: "businessDictionary/fetchf",
				payload: { search: searchValue },
				callback: (res) => {
					let filename = decodeURIComponent(res.requestRes.headers.get("Content-Disposition").split("=")[1]);
					download.byBlob(res.fileBlob, filename);
				},
			});
		}
	};

	impTemp = () => {
		const { dispatch, currentUser } = this.props;
		dispatch({
			type: "businessDictionary/fetche",
			payload: {},
			callback: (res) => {
				let filename = decodeURIComponent(res.requestRes.headers.get("Content-Disposition").split("=")[1]);
				download.byBlob(res.fileBlob, filename);
			},
		});
	};

	handleDeletes = (e) => {
		Modal["confirm"]({
			title: `删除任务`,
			content: "确定删除吗？",
			okText: "删除",
			cancelText: "取消",
			onOk: () => {
				console.log(e);
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "businessDictionary/fetchc",
						payload: { id: e.id },
						callback: (res) => {
							message["info"](`${res.message}`);
							this.fetch(this.state.searchValue);
						},
					});
				});
			},
			onCancel() { },
		});
	};

	enumeration = () => {
		this.setState({ showModel: true });
	};

	leadWay = () => {
		this.setState({ showModelA: true, fileList: [] });
	};

	handleUpFile = (info) => {
		let fileList = [...info.fileList];
		fileList = fileList.slice(-1);
		fileList = fileList.map((file) => {
			if (file.response) {
				file.url = file.response.url;
			};
			return file;
		});
		if (fileList[0].size / 1024 / 1024 > 2) {
			// 2000000
			message.error("上传文件超出2M");
			this.setState({ fileList: [] });
		} else {
			this.setState({ fileList });
		}
	};

	uploadFile = (data) => {
		const { dispatch } = this.props;
		dispatch({
			type: "businessDictionary/fetchg",
			payload: data,
			callback: (res) => {
				this.setState({ uploading: false, }, () => {
					this.setState({ showModelA: false, visible: false, fileList: [], page: 1, }, () => {
						this.fetch(this.state.searchValue, this.state.page, this.state.pageSize);
						if (res.data.msg) {
							message.success(res.data.msg);
						} else {
							message.success("导入成功");
						}
					});
				});
			},
		});
	};

	businessWayA = () => {
		const { fileList } = this.state;
		const formData = new FormData();
		fileList.forEach((file) => {
			formData.append("file", file.originFileObj);
		});
		this.setState({ uploading: true });
		this.uploadFile(formData);
	};

	handleCancel = () => {
		this.setState({ showModelA: false, uploading: false, fileList: [] });
	};

	showRev = (a, b) => {
		this.setState({ pdx: b });
	};

	showRevS = (a, b) => {
		this.setState({ pdx: null });
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		const FormItemLayont = {
			labelCol: {
				xs: 24,
				sm: 5,
			},
			wrapperCol: {
				xs: 24,
				sm: 19,
			},
		};
		const { uploading, fileList } = this.state;
		const props = {
			// name: 'file',
			// headers: headData,
			// action: '/basic/lexicon/import',
			// accept: '.xlsx',
			// onChange: this.handleChangeByUpload,
			onRemove: (file) => {
				this.setState((state) => {
					const index = state.fileList.indexOf(file);
					const newFileList = state.fileList.slice();
					newFileList.splice(index, 1);
					return {
						fileList: newFileList,
					};
				});
			},
			beforeUpload: (file) => {
				this.setState((state) => ({
					fileList: [...state.fileList, file],
				}));
				return false;
			},
			accept: ".xls",
			fileList,
			onChange: this.handleUpFile,
		};

		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<div className={styles.backgroundp}>
						<Row className={styles.colorBackground}>
							<Col style={{ padding: 10, color: "#4B5475", fontWeight: 600 }} xs={24}>
								<div className={styles.title}>
									<span>业务词库{`(${this.state.total})`}</span>
									<span style={{ marginLeft: 2, paddingTop: 2 }}>
										<Tooltip placement='top' title='即客户公司专有的一些专业性业务名词，如“花呗”对于支付宝来说就是专业性业务名词。' arrowPointAtCenter>
											<Icon type='info-circle' />
										</Tooltip>
									</span>
								</div>
							</Col>
						</Row>
						<Card bordered={false}>
							<div>
								<div className={styles.fromColumn} style={{ textAlign: 'right' }}>
									<span className='buttonYs'>
										<Button onClick={this.enumeration} type="primary">新增</Button>
									</span>
									<span className='buttonYs'>
										<Button onClick={this.leadWay}>导入</Button>
									</span>
									<span className='buttonYs'>
										<Button onClick={this.answerDetail}>导出</Button>
									</span>
								</div>

								<Spin spinning={this.state.login}>
									<div className={styles.Tag}>
										<div style={{ paddingTop: 5 }} className={styles.tagS}>
											{this.state.total != 0 ? null : (
												<div className={styles.empty}> <img src={emptys} /> </div>
											)}
											{this.state.thesaurusList.map((item, index) => {
												let color = index % 2 == 1 ? { backgroundColor: "#e8eff6" } : { backgroundColor: "#e8eff6" };
												let padding = this.state.pdx === index ? { padding: "7px 3px 7px 23px", backgroundColor: "rgb(232, 239, 216)", } : { padding: "7px 23px", backgroundColor: "#e8eff6", };
												return (
													<Suspense key={item.id}>
														<span onMouseOut={() => this.showRevS(item, index)} onMouseOver={() => this.showRev(item, index)} style={padding} key={item.id} className={styles.tag}>
															{item.dict}
															{this.state.pdx === index ? (
																<img onClick={() => this.handleDeletes(item)} className={styles.imgyd} src={x} />
															) : (
																<img style={{ display: "none" }} className={styles.imgyd} src={x} />
															)}
														</span>
													</Suspense>
												);
											})}
										</div>
									</div>
								</Spin>

								<Modal
									className='modelZdy'
									title={<FormattedMessage id='app.businessDictionary.add-word' />}
									visible={this.state.showModel}
									okText={<FormattedMessage id='app.customDictionary.save' />}
									cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
									onCancel={() => {
										this.props.form.setFields({ businessName: "" });
										this.setState({ showModel: false });
									}}
									onOk={this.businessWay} // 确定方法开出去
								>
									<Form layout='horizontal'>
										<FormItem label='业务词名称' onSubmit={this.coreWordOne} {...FormItemLayont}>
											{getFieldDecorator("businessName", {
												initialValue: "",
												rules: [
													{ required: true, message: "用户词名称不能为空" },
													(rule, value = "", callback) => {
														try {
															if (value.length > 20) {
																callback("用户词名称不可超过20个字符");
															}
															callback();
														} catch (err) {
															callback(err);
														}
													},
												],
											})(<Input onPressEnter={this.businessWay} />)}
										</FormItem>
									</Form>
								</Modal>

								<Modal
									className='modelZdy'
									width={550}
									title={<FormattedMessage id='app.businessDictionary.puload-word' />}
									visible={this.state.showModelA}
									footer={[
										<Button key='back' onClick={this.handleCancel}>取消</Button>,
										<Button key='submit' type='primary' loading={uploading} disabled={fileList.length === 0} onClick={this.businessWayA}>{uploading ? "导入中" : "开始导入"}</Button>,
									]}
									onCancel={() => {
										this.setState({ showModelA: false, uploading: false });
									}}
								>
									<Form layout='horizontal'>
										<FormItem label='选择文件' onSubmit={this.coreWordOne} {...FormItemLayont}>
											<Upload {...props} fileList={this.state.fileList}>
												<Button><Icon type='upload' /> 选择文件</Button>
											</Upload>
										</FormItem>
										<FormItem label='上传规则' onSubmit={this.coreWordOne} {...FormItemLayont}>
											<div className={styles.frame}>
												<div>
													<span>• 请按照模板中的示例格式进行编辑上传：</span>{" "}
													<span onClick={this.impTemp} className={styles.template}>下载xls模版</span>
												</div>
												<div>
													<span>• 上传文件格式需要为“.xls”类型的Excel文件</span>
												</div>
												<div>
													<span>• 导入的业务词数据将覆盖现有数据，请谨慎操作</span>
												</div>
											</div>
										</FormItem>
									</Form>
								</Modal>
							</div>
						</Card>
					</div>
				</PageHeaderWrapper>
			</Suspense>
		);
	}

	onChange = (e) => {
		this.setState({ page: e }, () => {
			this.fetch(this.state.searchValue, this.state.page, this.state.pageSize);
		});
	};

	onShowSizeChange = (a, b) => {
		this.setState({ pageSize: b, page: a }, () => {
			this.fetch(this.state.searchValue, this.state.page, this.state.pageSize);
		});
	};

	businessWays = (e) => {
		let sj = e.target.value;
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		this.props.form.validateFields((err, values) => {
			// 校验方法
			if (!err) {
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "businessDictionary/fetchb",
						payload: {
							token: currentUser.token,
							robotId: currentUser.robotId,
							termName: sj,
						},
						callback: (res) => {
							if (res.code === 0) {
								message["success"](`${res.msg}`);
								// this.setState({ showModel: false });
								this.fetch(this.state.searchValue, this.state.page, this.state.pageSize);
								this.props.form.setFields({ businessName: "" });
							}
						},
					});
				});
			}
		});
	};

	businessWay = () => {
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		this.props.form.validateFields((err, values) => {
			// 校验方法
			if (!err) {
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "businessDictionary/fetchb",
						payload: {
							dict: userInfo.businessName,
						},
						callback: (res) => {
							if (typeof res.code !== 'undefined' && res.code !== 0) {
								// message["error"](`${res.message}`);
							} else {
								message["info"](`${res.message}`);
								this.setState({ showModel: false });
								this.fetch(this.state.searchValue, this.state.page, this.state.pageSize);
								this.props.form.setFields({ businessName: "" });
							}
						},
					});
				});
			}
		});
	};
}

export default connect(({ user }) => ({
	// 全局数据
	currentUser: user.currentUser,
}))(Form.create()(BusinessDictionary));
